﻿/*----------------------------------------------------------------
//  <copyright file="DefaultEmailSender.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2023-12-06 10:46</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud
{
    #region "默认邮件发送功能-暂留备查"
    /// <summary>
    /// 默认邮件发送者-暂留备查
    /// </summary>
    public class DefaultEmailSender /*: IEmailSender*/
    {
        //字段
        private readonly ILogger _logger;
        private readonly MicroCloudOptions _options;

        #region "构造函数"
        #region "初始化一个默认邮件发送者 <see cref="DefaultEmailSender"/> 的新实例"
        /// <summary>
        /// 初始化一个默认邮件发送者 <see cref="DefaultEmailSender"/> 的新实例
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public DefaultEmailSender(IServiceProvider provider)
        {
            _logger = provider.GetLogger<DefaultEmailSender>();
            _options = provider.GetMicroCloudOptions();
        }
        #endregion

        #endregion

        #region "方法"
        #region "异步发送邮件"
        /// <summary>
        /// 异步发送邮件
        /// </summary>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件正文内容</param>
        /// <param name="bodyFormat">邮件正文格式</param>
        /// <param name="bccEmails">密送</param>
        /// <param name="ccEmails">抄送</param>
        /// <param name="toEmails">收件人</param>
        /// <returns></returns>
        public async Task SendEmailAsync(string subject, string body, EmailBodyFormat bodyFormat = EmailBodyFormat.Html, string[] bccEmails = null, string[] ccEmails = null, params string[] toEmails)
        {
            var mailSender = _options?.Email?.Sender;
            if (mailSender == null || mailSender.Host == null || mailSender.Host.Contains("请替换"))
            {
                throw new Exception(I18N.T("邮件发送选项不存在，请在 appsettings.json 配置 MicroCloud:Email:Sender 节点"));
            }

            string host = mailSender.Host,
                displayName = mailSender.DisplayName,
                userName = mailSender.UserName,
                password = mailSender.Password;
            bool enableSsl = mailSender.EnableSsl, useDefaultCredentials = false;
            int port = mailSender.Port;
            SmtpClient client = new(host);
            if (port > 0)
            {
                //port = enableSsl ? 465 : 25;
                client.Port = port;
            }
            client.EnableSsl = enableSsl;
            //验证 用户名 密码 
            client.Credentials = new NetworkCredential(userName, password);
            //是否请求一起发送 
            client.UseDefaultCredentials = useDefaultCredentials;
            //设置邮件发送格式 
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            string fromEmail = userName.Contains('@') ? userName : "{0}@{1}".FormatWith(userName, client.Host.Replace("smtp.", ""));
            MailMessage mail = new()
            {
                //邮件发送方
                From = new MailAddress(fromEmail, displayName),
                //邮件主题
                Subject = subject,
                //邮件正文格式 
                BodyEncoding = Encoding.UTF8,
                //邮件正文内容
                Body = body,
                //邮件正文是否为HTML格式
                IsBodyHtml = bodyFormat == EmailBodyFormat.Html,
            };

            if (bccEmails != null && bccEmails.Length > 0)
            {
                foreach (var bccEmail in bccEmails)
                {
                    mail.Bcc.Add(bccEmail);
                }
            }
            if (ccEmails != null && ccEmails.Length > 0)
            {
                foreach (var ccEmail in ccEmails)
                {
                    mail.CC.Add(ccEmail);
                }
            }
            if (toEmails == null || toEmails.Length <= 0)
            {
                throw new Exception(I18N.T("邮件收件人不能为空"));
            }
            foreach (var toEmail in toEmails)
            {
                mail.To.Add(toEmail);
            }

            await client.SendMailAsync(mail);
            var ccStr = "";
            if (mail.CC.Count > 0)
            {
                ccStr = $"，抄送到“{mail.CC.ExpandAndToString()}”";
            }
            var bccStr = "";
            if (mail.Bcc.Count > 0)
            {
                bccStr = $"，密送到“{mail.Bcc.ExpandAndToString()}”";
            }
            _logger.LogDebug("发送邮件到 {to} {ccStr}{bccStr}，标题：{subject}。", mail.To.ExpandAndToString(), ccStr, bccStr, mail.Subject);

        }
        #endregion
        #region "异步发送邮件"
        /// <summary>
        /// 异步发送邮件
        /// </summary>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件正文内容</param>
        /// <param name="bodyFormat">邮件正文格式</param>
        /// <param name="ccEmails">抄送</param>
        /// <param name="toEmails">收件人</param>
        /// <returns></returns>
        public async Task SendEmailAsync(string subject, string body, EmailBodyFormat bodyFormat = EmailBodyFormat.Html, string[] ccEmails = null, params string[] toEmails)
        {
            await SendEmailAsync(subject, body, bodyFormat, null, ccEmails, toEmails);
        }
        #endregion
        #region "异步发送邮件"
        /// <summary>
        /// 异步发送邮件
        /// </summary>
        /// <param name="subject">邮件主题</param>
        /// <param name="body">邮件正文内容</param>
        /// <param name="bodyFormat">邮件正文格式</param>
        /// <param name="toEmails">收件人</param>
        /// <returns></returns>
        public async Task SendEmailAsync(string subject, string body, EmailBodyFormat bodyFormat = EmailBodyFormat.Html, params string[] toEmails)
        {
            await SendEmailAsync(subject, body, bodyFormat, null, null, toEmails);
        }
        #endregion

        #endregion

    }
    #endregion

}
